package com.example.servicestest

import android.content.ComponentName
import android.content.Context
import android.content.Intent
import android.content.ServiceConnection
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.os.IBinder
import android.util.Log
import kotlinx.android.synthetic.main.activity_service.*

class ServiceActivity : AppCompatActivity() {

    lateinit var downloadBinder : MyService.DownloadBinder
    val TAG = "ServiceActivity"

    private val connection = object : ServiceConnection{
        //绑定成功
        override fun onServiceConnected(name: ComponentName?, service: IBinder?) {
            downloadBinder = service as MyService.DownloadBinder
            //下面这个也可以都放在其他地方调用
            downloadBinder.startDownload()
            downloadBinder.getProgress()
            Log.d(TAG, "onServiceConnected: 绑定Service成功")
        }
        //解绑时调用
        override fun onServiceDisconnected(name: ComponentName?) {
            Log.d(TAG, "onServiceDisconnected: 解绑成功")
        }

    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_service)

        val intent = Intent(this,MyService::class.java)

        startServiceBtn.setOnClickListener {
            startService(intent)    //开启service
        }

        stopServiceBtn.setOnClickListener {
            stopService(intent)     //停止service
            //在service内部停止 调用stopSelf()
        }

        bindServiceBtn.setOnClickListener {
            bindService(intent,connection, Context.BIND_AUTO_CREATE)    //绑定service
        }
        unbindServiceBtn.setOnClickListener {
            unbindService(connection)
        }

        startForeServiceBtn.setOnClickListener {
            val intent2 = Intent(this,ForegroundService::class.java)

            startService(intent2)
        }

        stopForeServiceBtn.setOnClickListener {
            val intent2 = Intent(this,ForegroundService::class.java)
            stopService(intent2)
        }

    }
}